<template>
  <div>
    <el-card style="margin: 20px 20px 0">
      <el-form :inline="true">
        <el-form-item label="一级分类">
          <el-select
            placeholder="请选择"
            v-model="category1Id"
            @change="getCategory2List"
          >
            <el-option
              :label="c1.name"
              :value="c1.id"
              v-for="c1 in category1List"
              :key="c1.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select
            placeholder="请选择"
            @change="getCategory3List"
            v-model="category2Id"
          >
            <el-option
              :label="c2.name"
              :value="c2.id"
              v-for="c2 in category2List"
              :key="c2.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="三级分类">
          <el-select
            placeholder="请选择"
            v-model="category3Id"
            @change="handleCategory3"
          >
            <el-option
              :label="c3.name"
              :value="c3.id"
              v-for="c3 in category3List"
              :key="c3.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "CategorySelector",
  data() {
    return {
      category1Id: "", //初始化category1Id
      category2Id: "",
      category3Id: "",
    };
  },
  methods: {
    // 获取一级分类列表
    async getCategory1List() {
      await this.$store.dispatch("category/getCategory1List");
    },
    // 一级分类变化获取二级分类
    async getCategory2List() {
      // 一级分类列表变化 清空二级分类及三级分类数据
      this.$store.commit("category/UPDATE_CATEGORY2ID", "");
      this.$store.commit("category/UPDATE_CATEGORY3ID", "");

      this.category2Id = "";
      this.category3Id = "";

      // 获取二级分类列表
      await this.$store.dispatch("category/getCategory2List", this.category1Id);
      // 修改仓库内一级分类的id
      this.$store.commit("category/UPDATE_CATEGORY1ID", this.category1Id);
    },
    // 二级分类变化获取三级分类
    async getCategory3List() {
      this.$store.commit("category/UPDATE_CATEGORY3ID", "");
      this.category3Id = "";

      await this.$store.dispatch("category/getCategory3List", this.category2Id);
      this.$store.commit("category/UPDATE_CATEGORY2ID", this.category2Id);
    },
    // 修改三级分类id
    handleCategory3() {
      this.$store.commit("category/UPDATE_CATEGORY3ID", this.category3Id);
    },
  },
  async mounted() {
    await this.getCategory1List();
  },
  computed: {
    ...mapState("category", [
      "category1List",
      "category2List",
      "category3List",
    ]),
  },
};
</script>

<style lang="less" scoped></style>
